package com.cwd.arm.inter.conf.AuthHandler;

import com.cwd.arm.inter.vo.ResponseVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yan on 21-11-19.
 */
public class FailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String errorMsg = null;
        if(e instanceof UsernameNotFoundException){
            errorMsg = "不存在该账号";
        }else{
            errorMsg = "请填写正确的账号或者密码";
        }
        out.write(new ObjectMapper().writeValueAsString(ResponseVo.<AuthenticationException>BUILDER().ERROR(errorMsg)));
        out.flush();
        out.close();
    }
}
